import {UserType} from '../../reducers/user';
import _ from 'lodash';
import {OrderState, OrderStateColor} from '../../reducers/order-list';
import {I18n} from '../../reducers/intl';
import {ConvertProduct, formatDate, getRealSize, Touchable} from '../../utils';
import {StyleSheet, Text, View} from 'react-native';
import React from 'react';
import Product from './product';
import PropTypes from 'prop-types';
import Button from '../button';

class Order extends React.Component {
  static propTypes = {
    item: PropTypes.object,
    categories: PropTypes.object,
    order: PropTypes.object,
    userType: PropTypes.string,
    userId: PropTypes.number,
    onConfirmChange: PropTypes.func,
    onOrder: PropTypes.func,
  };

  static defaultProps = {
    item: {},
    categories: {},
    order: {},
    onConfirmChange: () => {},
    onOrder: () => {},
  };

  confirm = field => {
    const {onConfirmChange} = this.props;
    if (onConfirmChange) {
      onConfirmChange(field);
    }
  };

  renderActions = () => {
    const {order, userType, userId} = this.props;
    let role = '';
    if ([UserType.provider, UserType.technician].includes(userType)) {
      role = 'seller';
    } else {
      role = 'buyer';
    }
    const roleId = _.get(order, `${role}.id`, '');
    const selfOrder = roleId === userId;
    const disabled = order.cancelled || order.refused;
    const actions = [];

    if (
      [UserType.technician, UserType.provider].includes(userType) &&
      order.state === OrderState.ORDERING &&
      selfOrder &&
      !disabled
    ) {
      actions.push(
        <Button
          label={I18n.t('order.action.refuse')}
          style={Styles.btn}
          key="refuse"
          type="ghost"
          size="small"
          onPress={() => this.confirm('refuse')}
        />,
      );
      actions.push(
        <Button
          label={I18n.t('order.action.confirm')}
          style={Styles.btn}
          key="confirm"
          type="ghost"
          size="small"
          onPress={() => this.confirm('confirm')}
        />,
      );
    }

    if (
      [UserType.technician, UserType.provider].includes(userType) &&
      order.state === OrderState.CONFIRMEN &&
      selfOrder &&
      !disabled
    ) {
      actions.push(
        <Button
          label={I18n.t('order.action.deliver')}
          style={Styles.btn}
          key="deliver"
          type="ghost"
          size="small"
          onPress={() => this.confirm('deliver')}
        />,
      );
    }

    if (
      [UserType.dentist, UserType.clinic].includes(userType) &&
      order.state === OrderState.ORDERING &&
      selfOrder &&
      !disabled
    ) {
      actions.push(
        <Button
          label={I18n.t('order.action.cancel')}
          style={Styles.btn}
          key="cancel"
          type="ghost"
          size="small"
          onPress={() => this.confirm('cancel')}
        />,
      );
    }
    if (
      [UserType.dentist, UserType.clinic].includes(userType) &&
      order.state === OrderState.DELIVERY &&
      selfOrder &&
      !disabled
    ) {
      actions.push(
        <Button
          label={I18n.t('order.action.receive')}
          style={Styles.btn}
          key="receive"
          type="ghost"
          size="small"
          onPress={() => this.confirm('receive')}
        />,
      );
    }

    if (
      [UserType.dentist, UserType.clinic].includes(userType) &&
      order.state === OrderState.RECEIVED &&
      selfOrder &&
      !disabled
    ) {
      actions.push(
        <Button
          label={I18n.t('order.action.paid')}
          style={Styles.btn}
          key="paid"
          type="ghost"
          size="small"
          onPress={() => this.confirm('paid')}
        />,
      );
    }

    if (
      [UserType.technician, UserType.provider].includes(userType) &&
      order.state === OrderState.PAID &&
      selfOrder &&
      !disabled
    ) {
      actions.push(
        <Button
          label={I18n.t('order.action.assure')}
          style={Styles.btn}
          key="assure"
          type="ghost"
          size="small"
          onPress={() => this.confirm('assure')}
        />,
      );
    }

    if (
      [UserType.dentist, UserType.clinic].includes(userType) &&
      order.state === OrderState.ASSURE &&
      selfOrder &&
      !disabled
    ) {
      actions.push(
        <Button
          label={I18n.t('order.action.comment')}
          style={Styles.btn}
          key="comment"
          type="ghost"
          size="small"
          onPress={() => this.confirm('comment')}
        />,
      );
    }

    if (actions.length) {
      return <View style={Styles.action}>{actions}</View>;
    }
    return null;
  };

  render() {
    const {order, categories, onOrder} = this.props;

    let stat = order.state;
    if (order.cancelled) {
      stat = OrderState.CANCELLED;
    } else if (order.refused) {
      stat = OrderState.REFUSED;
    }
    const orderAttr = [];
    orderAttr.push(`医生:${_.get(order, 'buyer.clinic_name')}`);
    orderAttr.push(`技师:${_.get(order, 'seller.vendor_name')}`);
    orderAttr.push(
      `${I18n.t('order.props.patient.name')}:${order.patient_name}`,
    );
    orderAttr.push(`${I18n.t('order.props.patient.age')}:${order.patient_age}`);
    orderAttr.push(
      `${I18n.t('order.props.patient.gender')}:${order.patient_gender}`,
    );
    const products = order.items.map(item => {
      return ConvertProduct(item, categories);
    });
    return (
      <View style={Styles.box}>
        <Touchable onPress={() => onOrder()}>
          <View style={Styles.content}>
            <View style={Styles.head}>
              <Text style={Styles.title}>{order.order_no}</Text>
              <Text style={Styles.time}>
                {formatDate(order.created, 'YYYY-MM-DD HH:mm:ss')}
              </Text>
            </View>
            <View style={Styles.product}>
              {products.map(item => (
                <Product item={item} key={item.uid} />
              ))}
            </View>
            <View style={Styles.props}>
              <Text style={Styles.extra}>{orderAttr.join(' / ')}</Text>
            </View>
          </View>
        </Touchable>
        <View style={Styles.foot}>
          <Text style={[Styles.state, {color: OrderStateColor[order.state]}]}>
            {stat}
          </Text>
          {this.renderActions()}
        </View>
      </View>
    );
  }
}

export default Order;

const Styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  box: {
    backgroundColor: '#f7f7f7',
    marginHorizontal: getRealSize(15),
    borderRadius: getRealSize(4),
  },
  content: {
    paddingHorizontal: getRealSize(15),
    paddingTop: getRealSize(15),
  },
  head: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
  },
  title: {
    color: '#333',
    fontWeight: 'bold',
    flex: 1,
  },
  time: {
    fontSize: getRealSize(12),
    fontWeight: '400',
    color: '#757575',
    textAlign: 'right',
  },
  extra: {
    fontSize: getRealSize(12),
    fontWeight: '400',
    color: '#757575',
  },
  props: {
    marginVertical: getRealSize(8),
  },
  state: {},
  foot: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingHorizontal: getRealSize(15),
    borderTopWidth: StyleSheet.hairlineWidth,
    borderTopColor: '#ccc',
    paddingTop: getRealSize(8),
    paddingBottom: getRealSize(8),
  },
  action: {
    flex: 1,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'flex-end',
  },
  btn: {
    // marginLeft: getRealSize(8),
  },
});
